package com.example.triprec.dao;

import android.annotation.SuppressLint;
import android.content.ContentValues;
import android.database.Cursor;

import com.example.triprec.common.Result;
import com.example.triprec.common.ScenicData;
import com.example.triprec.entity.Collect;
import com.example.triprec.entity.User;
import com.example.triprec.utils.SqliteUtils;
import com.gzone.university.utils.DateUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 收藏数据访问对象
 */
@SuppressLint("Range")
public class CollectDao {

    /**
     * 添加收藏
     */
    public static Result<Void> addCollect(Long userId, Long scenicId) {
        if (userId == null || scenicId == null) {
            return new Result<>(false, "用户ID或景点ID不能为空", null);
        }

        // 检查是否已收藏
        Result<Boolean> isCollectedResult = isCollected(userId, scenicId);
        if (isCollectedResult.isSuccess() && Boolean.TRUE.equals(isCollectedResult.getData())) {
            return new Result<>(false, "已收藏该景点", null);
        }

        String currentTime = DateUtils.format(new Date());

        ContentValues values = new ContentValues();
        values.put("user_id", userId);
        values.put("scenic_id", scenicId);
        values.put("create_time", currentTime);

        long i = SqliteUtils.getInstance().getWritableDatabase().insert("tb_collect", null, values);
        if (i > 0) {
            return new Result<>(true, "收藏成功", null);
        }
        return new Result<>(false, "收藏失败", null);
    }

    /**
     * 取消收藏
     */
    public static Result<Void> cancelCollect(Long userId, Long scenicId) {
        if (userId == null || scenicId == null) {
            return new Result<>(false, "用户ID或景点ID不能为空", null);
        }

        int i = SqliteUtils.getInstance().getWritableDatabase().delete("tb_collect", "user_id=? AND scenic_id=?", new String[]{String.valueOf(userId), String.valueOf(scenicId)});
        if (i > 0) {
            return new Result<>(true, "取消收藏成功", null);
        }
        return new Result<>(false, "取消收藏失败", null);
    }

    /**
     * 根据收藏ID取消收藏
     */
    public static Result<Void> cancelCollectById(Long collectId) {
        if (collectId == null) {
            return new Result<>(false, "收藏ID不能为空", null);
        }

        int i = SqliteUtils.getInstance().getWritableDatabase().delete("tb_collect", "id=?", new String[]{String.valueOf(collectId)});
        if (i > 0) {
            return new Result<>(true, "取消收藏成功", null);
        }
        return new Result<>(false, "取消收藏失败", null);
    }

    /**
     * 判断用户是否已收藏景点
     */
    public static Result<Boolean> isCollected(Long userId, Long scenicId) {
        if (userId == null || scenicId == null) {
            return new Result<>(false, "用户ID或景点ID不能为空", null);
        }

        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_collect", null, "user_id=? AND scenic_id=?", new String[]{String.valueOf(userId), String.valueOf(scenicId)}, null, null, null);
        boolean isCollected = cursor.getCount() > 0;
        cursor.close();

        return new Result<>(true, "查询成功", isCollected);
    }

    /**
     * 获取用户收藏列表
     */
    public static Result<List<Collect>> getCollectsByUserId(Long userId) {
        if (userId == null) {
            return new Result<>(false, "用户ID不能为空", null);
        }

        List<Collect> collectList = new ArrayList<>();
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().query("tb_collect", null, "user_id=?", new String[]{String.valueOf(userId)}, null, null, "create_time DESC");

        while (cursor.moveToNext()) {
            Collect collect = extractCollectFromCursor(cursor);

            // 关联景点信息和用户信息
            collect.setScenic(ScenicData.getScenicById(collect.getScenicId()));

            Result<User> userResult = UserDao.getByUserId(collect.getUserId());
            if (userResult.isSuccess()) {
                collect.setUser(userResult.getData());
            }

            collectList.add(collect);
        }
        cursor.close();

        if (!collectList.isEmpty()) {
            return new Result<>(true, "查询成功", collectList);
        } else {
            return new Result<>(true, "暂无收藏", collectList);
        }
    }

    /**
     * 获取景点被收藏数量
     */
    public static Result<Integer> getCollectCountByScenicId(Long scenicId) {
        if (scenicId == null) {
            return new Result<>(false, "景点ID不能为空", null);
        }

        String sql = "SELECT COUNT(*) as count FROM tb_collect WHERE scenic_id = ?";
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().rawQuery(sql, new String[]{String.valueOf(scenicId)});

        int count = 0;
        if (cursor.moveToFirst()) {
            count = cursor.getInt(cursor.getColumnIndex("count"));
        }
        cursor.close();

        return new Result<>(true, "获取收藏数量成功", count);
    }

    /**
     * 获取用户收藏数量
     */
    public static Result<Integer> getCollectCountByUserId(Long userId) {
        if (userId == null) {
            return new Result<>(false, "用户ID不能为空", null);
        }

        String sql = "SELECT COUNT(*) as count FROM tb_collect WHERE user_id = ?";
        Cursor cursor = SqliteUtils.getInstance().getReadableDatabase().rawQuery(sql, new String[]{String.valueOf(userId)});

        int count = 0;
        if (cursor.moveToFirst()) {
            count = cursor.getInt(cursor.getColumnIndex("count"));
        }
        cursor.close();

        return new Result<>(true, "获取收藏数量成功", count);
    }

    /**
     * 从游标中提取收藏信息
     */
    private static Collect extractCollectFromCursor(Cursor cursor) {
        Collect collect = new Collect();
        collect.setId(cursor.getLong(cursor.getColumnIndex("id")));
        collect.setUserId(cursor.getLong(cursor.getColumnIndex("user_id")));
        collect.setScenicId(cursor.getLong(cursor.getColumnIndex("scenic_id")));
        collect.setCreateTime(cursor.getString(cursor.getColumnIndex("create_time")));

        return collect;
    }
} 